package com.xtianzhuang.www.aspect;

import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.xtianzhuang.www.dao.TlOperateLogMapper;
import com.xtianzhuang.www.entity.TlOperateLog;
import com.xtianzhuang.www.entity.subject.UserSubject;
import com.xtianzhuang.www.utils.SingletonFactory;

/**
 * 
 * @author xtian.zhuang
 *
 */
@Aspect
@Component
public class LogOperateAspect {
	private static Logger logger = LoggerFactory.getLogger(LogOperateAspect.class);
	@Autowired
	private TlOperateLogMapper tlOperateLogMapper;
	@Pointcut("@annotation(com.xtianzhuang.www.annotation.LogOperate)")
	public void logAspect() {

	}

	// @Before("logAspect()")
	// public void logBofore(JoinPoint joinPoint) {
	// Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
	// if (method != null) {
	// Log log = method.getAnnotation(Log.class);
	// logger.debug("------------------------" + method.getName() + ": " + log.type()
	// + "------------------------ start");
	// String msg = "";
	// Class<?>[] params = method.getParameterTypes();
	// Object[] args = joinPoint.getArgs();
	// for (int i = 0; i < args.length; i++) {
	// msg += params[i].getName() + "[param" + (i + 1) + "]" + "="
	// + new JSONSerializer().deepSerialize(args[i]) + "\n";
	// }
	// logger.debug(msg);
	//
	// }
	// }
	//
	// @After("logAspect()")
	// public void logAfter(JoinPoint joinPoint) {
	// Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
	// if (method != null) {
	// Log log = method.getAnnotation(Log.class);
	// logger.debug(
	// "------------------------" + method.getName() + ": " + log.type() + "------------------------ end");
	// }
	// }

	@After("logAspect()")
	public void doSurround(JoinPoint joinPoint) throws Throwable {
		Object[] objects = joinPoint.getArgs();
		String name = joinPoint.getSignature().getName();
		String msg = "";
		for (int i = 0; i < objects.length; i++) {
			try {
				msg += "[param" + (i + 1) + "]" + "=" + JSON.toJSONString(objects[i]) + "\n";
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		UserSubject subject = SingletonFactory.getInstance(UserSubject.class);
		TlOperateLog tlOperateLog = new TlOperateLog();
		tlOperateLog.setInterfaceName(name);
		tlOperateLog.setParam(msg);
		tlOperateLog.setCreateTime(new Date());
		tlOperateLog.setCreateStaffId(subject.getPrincipal().getUserName());
		tlOperateLogMapper.insert(tlOperateLog);
	}

}
